import React, { useEffect } from 'react';
import {
  Modal,
  Form,
  Input,
  Select,
  Switch,
  Row,
  Col,
  message,
  Typography
} from 'antd';
import { 
  CreateRuleRequest, 
  UpdateRuleRequest, 
  CompatibilityRule,
  createCompatibilityRule,
  updateCompatibilityRule
} from '../../services/api';
import './RuleFormModal.css';

const { Option } = Select;
const { TextArea } = Input;
const { Text } = Typography;

interface RuleFormModalProps {
  visible: boolean;
  mode: 'create' | 'edit';
  initialValues?: CompatibilityRule;
  onCancel: () => void;
  onSuccess: () => void;
}

const RuleFormModal: React.FC<RuleFormModalProps> = ({
  visible,
  mode,
  initialValues,
  onCancel,
  onSuccess
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = React.useState(false);

  useEffect(() => {
    if (visible && initialValues && mode === 'edit') {
      form.setFieldsValue({
        ...initialValues,
        isActive: initialValues.isActive ?? true
      });
    } else if (visible && mode === 'create') {
      form.resetFields();
      form.setFieldsValue({
        isActive: true,
        severity: 'MEDIUM'
      });
    }
  }, [visible, initialValues, mode, form]);

  const handleSubmit = async () => {
    try {
      setLoading(true);
      const values = await form.validateFields();
      
      let response;
      if (mode === 'create') {
        const createRequest: CreateRuleRequest = {
          ruleId: values.ruleId,
          ruleName: values.ruleName,
          category: values.category,
          sourceDbType: values.sourceDbType,
          targetDbType: values.targetDbType,
          rulePattern: values.rulePattern,
          severity: values.severity,
          description: values.description,
          suggestion: values.suggestion,
          exampleSql: values.exampleSql || '',
          suggestedSql: values.suggestedSql || '',
          isActive: values.isActive
        };
        response = await createCompatibilityRule(createRequest);
      } else {
        const updateRequest: UpdateRuleRequest = {
          ruleName: values.ruleName,
          category: values.category,
          sourceDbType: values.sourceDbType,
          targetDbType: values.targetDbType,
          rulePattern: values.rulePattern,
          severity: values.severity,
          description: values.description,
          suggestion: values.suggestion,
          exampleSql: values.exampleSql || '',
          suggestedSql: values.suggestedSql || '',
          isActive: values.isActive
        };
        response = await updateCompatibilityRule(initialValues!.id, updateRequest);
      }

      if (response.success) {
        message.success(mode === 'create' ? '规则创建成功' : '规则更新成功');
        onSuccess();
      } else {
        message.error(response.message || `${mode === 'create' ? '创建' : '更新'}失败`);
      }
    } catch (error: any) {
      console.error(`${mode === 'create' ? '创建' : '更新'}规则失败:`, error);
      message.error(error.message || `${mode === 'create' ? '创建' : '更新'}失败`);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal
      title={mode === 'create' ? '新增规则' : '编辑规则'}
      open={visible}
      onCancel={onCancel}
      onOk={handleSubmit}
      confirmLoading={loading}
      width={800}
      className="rule-form-modal"
      destroyOnClose
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          isActive: true,
          severity: 'MEDIUM'
        }}
      >
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="ruleId"
              label="规则ID"
              rules={[
                { required: true, message: '请输入规则ID' },
                { pattern: /^[A-Z0-9_]+$/, message: '规则ID只能包含大写字母、数字和下划线' }
              ]}
            >
              <Input 
                placeholder="例如：RULE001" 
                disabled={mode === 'edit'}
                maxLength={50}
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="ruleName"
              label="规则名称"
              rules={[{ required: true, message: '请输入规则名称' }]}
            >
              <Input 
                placeholder="例如：Oracle CHAR类型转换规则" 
                maxLength={100}
              />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={8}>
            <Form.Item
              name="category"
              label="规则分类"
              rules={[{ required: true, message: '请选择规则分类' }]}
            >
              <Select placeholder="选择分类">
                <Option value="SYNTAX">语法</Option>
                <Option value="FUNCTION">函数</Option>
                <Option value="DATA_TYPE">数据类型</Option>
                <Option value="PERFORMANCE">性能</Option>
                <Option value="COMPATIBILITY">兼容性</Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="sourceDbType"
              label="源数据库类型"
              rules={[{ required: true, message: '请选择源数据库类型' }]}
            >
              <Select placeholder="选择源数据库">
                <Option value="MYSQL">MySQL</Option>
                <Option value="ORACLE">Oracle</Option>
                <Option value="POSTGRESQL">PostgreSQL</Option>
                <Option value="SQLSERVER">SQL Server</Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="targetDbType"
              label="目标数据库类型"
              rules={[{ required: true, message: '请选择目标数据库类型' }]}
            >
              <Select placeholder="选择目标数据库">
                <Option value="GOLDENDB">GoldenDB</Option>
                <Option value="MYSQL">MySQL</Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={16}>
            <Form.Item
              name="rulePattern"
              label="规则模式"
              rules={[{ required: true, message: '请输入规则模式' }]}
              extra={<Text type="secondary">支持正则表达式，用于匹配SQL语句</Text>}
            >
              <Input 
                placeholder="例如：CHAR\\(\\d+\\)" 
                maxLength={200}
              />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="severity"
              label="严重程度"
              rules={[{ required: true, message: '请选择严重程度' }]}
            >
              <Select>
                <Option value="HIGH">高危</Option>
                <Option value="MEDIUM">中危</Option>
                <Option value="LOW">低危</Option>
                <Option value="INFO">信息</Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Form.Item
          name="description"
          label="问题描述"
          rules={[{ required: true, message: '请输入问题描述' }]}
        >
          <TextArea 
            rows={3} 
            placeholder="描述此规则检测到的兼容性问题" 
            maxLength={500}
            showCount
          />
        </Form.Item>

        <Form.Item
          name="suggestion"
          label="修改建议"
          rules={[{ required: true, message: '请输入修改建议' }]}
        >
          <TextArea 
            rows={3} 
            placeholder="提供解决此兼容性问题的建议" 
            maxLength={500}
            showCount
          />
        </Form.Item>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="exampleSql"
              label="示例SQL"
              extra={<Text type="secondary">问题SQL示例（可选）</Text>}
            >
              <TextArea 
                rows={4} 
                placeholder="CREATE TABLE test (name CHAR(50));" 
                maxLength={1000}
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="suggestedSql"
              label="建议SQL"
              extra={<Text type="secondary">修正后的SQL示例（可选）</Text>}
            >
              <TextArea 
                rows={4} 
                placeholder="CREATE TABLE test (name VARCHAR(50));" 
                maxLength={1000}
              />
            </Form.Item>
          </Col>
        </Row>

        <Form.Item
          name="isActive"
          label="状态"
          valuePropName="checked"
        >
          <Switch checkedChildren="启用" unCheckedChildren="禁用" />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default RuleFormModal;